﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Add_ExportPartPlan : Form
    {
        private INISettings mySetting;
        private SqlConnection myConnection;
        private string error;
        public frm_Add_ExportPartPlan()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.error = null;
            this.inputDate.EditValue = DateTime.Now;
            CreateNewNumber();
            if (string.IsNullOrEmpty(error))
            {
                CreateNewONumber();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadStaff();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadCustomer();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadShipTo();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadPart();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadCurrency();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadDeliveryTerm();
            }
            if (string.IsNullOrEmpty(error))
            {
                LoadTransportation();
            }
            if (!string.IsNullOrEmpty(error))
            {
                MessageBox.Show(error);
            }
        }
        
        //////////////////////////////////
        /// Create New Number
        //////////////////////////////////
        private void CreateNewNumber()
        {
            string max_Number = null;
            int max_Index = 0;
            int max_year = 0;
            int new_index = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT MAX(Number) FROM [241_ExportPartPlan]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    max_Number = dataReader[0].ToString();
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Max Number";
            }

            if (!string.IsNullOrEmpty(max_Number))
            {
                max_Index = Int32.Parse(max_Number.Substring(4, 5));
                max_year = Int32.Parse(max_Number.Substring(1, 2));
                DateTime current_Date = DateTime.Now;
                int current_year = Int32.Parse(current_Date.Year.ToString().Substring(2));
                if (max_year < current_year)
                {
                    new_index = 1;
                }
                else
                {
                    new_index = max_Index + 1;
                }
                this.numberValue.Text = "P" + current_year.ToString("D2") + "A" + new_index.ToString("D5");
            }
            else
            {
                error = "Cannot create new Number";
            }
        }

        //////////////////////////////////
        /// Create New ONumber
        //////////////////////////////////
        private void CreateNewONumber()
        {
            string max_ONumber = null;
            int max_OIndex = 0;
            int max_Oyear = 0;
            int new_Oindex = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT MAX(OriginalNo) FROM [241_ExportPartPlan]";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    max_ONumber = dataReader[0].ToString();
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Max Original Number";
            }

            if (!string.IsNullOrEmpty(max_ONumber))
            {
                max_OIndex = Int32.Parse(max_ONumber.Substring(5, 5));
                max_Oyear = Int32.Parse(max_ONumber.Substring(1, 2));
                DateTime current_Date = DateTime.Now;
                int current_year = Int32.Parse(current_Date.Year.ToString().Substring(2));
                if (max_Oyear < current_year)
                {
                    new_Oindex = 1;
                }
                else
                {
                    new_Oindex = max_OIndex + 1;
                }
                this.originalNo.Text = "P" + current_year.ToString("D2") + "FN" + new_Oindex.ToString("D5");
            }
            else
            {
                error = "Cannot create new Original Number";
            }
        }

        ////////////////////////////////////////////
        /// Load Staff List to Input Person
        ////////////////////////////////////////////
        private void LoadStaff()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName FROM [222_Staff] ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffName"].ToString() + "(" + dataReader["StaffID"].ToString() + ")";
                    item.Value = dataReader["StaffID"].ToString();
                    this.inputPerson.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Staff list";
            }
        }

        ////////////////////////////////////////////
        /// Load Customer List
        ////////////////////////////////////////////
        private void LoadCustomer()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CustomerID, FullName FROM [222_Customer] ORDER BY FullName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["FullName"].ToString();
                    item.Value = dataReader["CustomerID"].ToString();
                    this.customerID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Customer list";
            }
        }

        ////////////////////////////////////////////
        /// Load Ship To
        ////////////////////////////////////////////
        private void LoadShipTo()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ShipToCode, ShipToName FROM [222_ShipTo] ORDER BY ShipToName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["ShipToName"].ToString();
                    item.Value = dataReader["ShipToCode"].ToString();
                    this.shipTo.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Ship To list";
            }
        }

        ////////////////////////////////////////////
        /// Load Part List
        ////////////////////////////////////////////
        private void LoadPart()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT EPartNo FROM [241_ExportPart] ORDER BY EPartNo";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["EPartNo"].ToString();
                    item.Value = dataReader["EPartNo"].ToString();
                    this.partNo.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Part list";
            }
        }

        ////////////////////////////////////////////
        /// Load Currency
        ////////////////////////////////////////////
        private void LoadCurrency()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT CurrencyID, CurrencySymbol FROM [222_Currency] ORDER BY CurrencySymbol";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["CurrencySymbol"].ToString();
                    item.Value = dataReader["CurrencyID"].ToString();
                    this.currencyID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Currency list";
            }
        }

        ////////////////////////////////////////////
        /// Load Delivery Term
        ////////////////////////////////////////////
        private void LoadDeliveryTerm()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DeliveryTermID, DeliveryTermName FROM [222_DeliveryTerm] ORDER BY DeliveryTermName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["DeliveryTermName"].ToString();
                    item.Value = dataReader["DeliveryTermID"].ToString();
                    this.deliveryTerm.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Delivery Term list";
            }
        }

        ////////////////////////////////////////////
        /// Load Transportation
        ////////////////////////////////////////////
        private void LoadTransportation()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT TransportID, TransportName FROM [222_Transport] ORDER BY TransportName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["TransportName"].ToString();
                    item.Value = dataReader["TransportID"].ToString();
                    this.transportationID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                error = "Cannot get Transportation list";
            }
        }

        ///////////////////////////////////
        /// Check if Number exist
        ///////////////////////////////////        
        private bool checkConflict(string number)
        {
            bool ret = true;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT COUNT(Number) FROM [241_ExportPartPlan] WHERE Number='" + number + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    int count = Int32.Parse(dataReader[0].ToString());
                    if (count > 0)
                    {
                        ret = false;
                    }
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                ret = false;
            }
            return ret;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error_add = null;
            if (!string.IsNullOrEmpty(error))
            {
                error_add = error;
            }
            string number, original, person = null, customer = null, shipto = null, planno, partno = null, poid;
            string cusplan, cusorder, delivery, transp, note;
            int qty = 0, currency = -1;
            DateTime? input, hopedeadline, fixdeadline, internaldeadline;
            input = DateTime.Now;
            hopedeadline = DateTime.Now;
            float unitprice = 0;
            ComboboxItem item = new ComboboxItem();            
             
            if (string.IsNullOrEmpty(error_add))
            {
                if (this.inputDate.EditValue == null)
                {
                    error_add = "Please select Input Date";
                }
                else
                {
                    input = DateTime.Parse(inputDate.DateTime.Date.ToString());
                }                
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (this.inputPerson.SelectedIndex == -1)
                {
                    error_add = "Please select Input Person";
                }
                else
                {
                    item = (ComboboxItem)inputPerson.SelectedItem;
                    person = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (this.customerID.SelectedIndex == -1)
                {
                    error_add = "Please select Customer";
                }
                else
                {
                    item = (ComboboxItem)customerID.SelectedItem;
                    customer = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (this.shipTo.SelectedIndex == -1)
                {
                    error_add = "Please select Ship To";
                }
                else
                {
                    item = (ComboboxItem)shipTo.SelectedItem;
                    shipto = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (this.partNo.SelectedIndex == -1)
                {
                    error_add = "Please select Part No";
                }
                else
                {
                    item = (ComboboxItem)this.partNo.SelectedItem;
                    partno = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (string.IsNullOrEmpty(this.quantityValue.Text.Trim()))
                {
                    error_add = "Please enter Quantity";
                }
                else
                {                    
                    bool isNum = Int32.TryParse(this.quantityValue.Text, out qty);
                    if (!isNum)
                    {
                        error_add = "Invalid Quantity value";
                    }
                }
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (this.hopeDeadline.EditValue == null)
                {
                    error_add = "Please select Hope Deadline";
                }
                else
                {
                    hopedeadline = DateTime.Parse(hopeDeadline.DateTime.Date.ToString());
                }
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (this.hopeDeadline.DateTime < this.inputDate.DateTime)
                {
                    error_add = "Hope Deadline must be greater than Input Date";
                }
            }

            if (string.IsNullOrEmpty(error_add))
            {
                if (string.IsNullOrEmpty(this.unitPrice.Text))
                {
                    unitprice = 0;
                }
                else
                {
                    bool isNum = float.TryParse(this.unitPrice.Text, out unitprice);
                    if (!isNum)
                    {
                        error_add = "Invalid Unit Price value";
                    }
                }
            }
            
            if (string.IsNullOrEmpty(error_add))
            {
                while (!checkConflict(this.numberValue.Text))
                {
                    CreateNewNumber();
                }
            } 
            
            if (string.IsNullOrEmpty(error_add))
            {                
                number = this.numberValue.Text;
                original = this.originalNo.Text;
                planno = this.planNo.Text;
                poid = this.poID.Text;
                cusplan = this.cusPlanNo.Text;
                cusorder = this.cusOrderNo.Text;
                

                if (this.currencyID.SelectedIndex == -1)
                {                    
                    for (int i = 0; i < this.currencyID.Properties.Items.Count; i++)
                    {
                        item = (ComboboxItem)this.currencyID.Properties.Items[i];
                        if (item.Text.ToString().Trim().ToUpper() == "NF")
                        {
                            currency = Int32.Parse(item.Value.ToString());                            
                        }
                    }
                }
                else
                {
                    item = (ComboboxItem)this.currencyID.SelectedItem;
                    currency = Int32.Parse(item.Value.ToString());
                }

                if (this.transportationID.SelectedIndex == -1)
                {
                    transp = "NF";
                }
                else
                {
                    item = (ComboboxItem)this.transportationID.SelectedItem;
                    transp = item.Value.ToString();
                }

                if (this.deliveryTerm.SelectedIndex == -1)
                {
                    delivery = "NF";
                }
                else
                {
                    item = (ComboboxItem)this.deliveryTerm.SelectedItem;
                    delivery = item.Value.ToString();
                }
                
                if (fixDeadline.EditValue == null)
                {
                    fixdeadline = null;
                }
                else
                {
                    fixdeadline = DateTime.Parse(this.fixDeadline.DateTime.Date.ToString());
                }

                if (internalDeadline.EditValue == null)
                {
                    internaldeadline = null;
                }
                else
                {
                    internaldeadline = DateTime.Parse(this.internalDeadline.DateTime.Date.ToString());
                }

                note = this.noteValue.Text;        

                try
                {
                    myConnection.Open();
                    string sql = "INSERT INTO [241_ExportPartPlan] (Number, InputDate, InputPerson, CustomerID,"
                        + " ShipToCode, PlanNo, PartNo, Quantity, POID, CusPlanNo, CusOrderNo, HopeDeadline, UnitPrice,"
                        + " CurrencyID, DeliveryTermID, TransportID, FixDeadline, InternalDeadline, Note, OriginalNo)"
                        + " VALUES ('" + number + "', @inputdate, '" + person + "', '" + customer + "', '" + shipto + "',"
                        + " '" + planno + "', '" + partno + "', " + qty + ", '" + poid + "', '" + cusplan + "', '" + cusorder + "',"
                        + " @hopedeadline, " + unitprice + ", " + currency + ", '" + delivery + "', '" + transp + "',"
                        + " @fixdeadline, @internaldeadline, '" + note + "', '" + original + "')";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@inputdate", SqlDbType.DateTime).Value = input.Value.Date;
                    cmd_sql.Parameters.Add("@hopedeadline", SqlDbType.DateTime).Value = hopedeadline.Value.Date;
                    cmd_sql.Parameters.Add("@fixdeadline", SqlDbType.DateTime).Value = (fixdeadline == null) ? (object)DBNull.Value : fixdeadline.Value.Date;
                    cmd_sql.Parameters.Add("@internaldeadline", SqlDbType.DateTime).Value = (internaldeadline == null) ? (object)DBNull.Value : internaldeadline.Value.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Export Part Plan added success.");
                    //this.Dispose();
                    clearForm();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    
                    MessageBox.Show("Cannot add Export Part Plan. Please try again.");
                }
            }
            else
            {                
                MessageBox.Show(error_add);
            }
        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c is DevExpress.XtraEditors.TextEdit)
                {
                    ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                }

                if (c is DevExpress.XtraEditors.ComboBoxEdit)
                {
                    ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                }

                if (c is System.Windows.Forms.MaskedTextBox)
                {
                    ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                }
            }
        }
    }
}
